//
//  NetworkManager.m
//  Untitled
//
//  Created by Hunk on 11-3-14.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "NetworkManager.h"
#import "WeiBoReachability.h"
#import "CJSONDeserializer.h"
#import "MyLoadingView.h"

@implementation NetworkManager

static NetworkManager* _sharedNetworkManager = nil;
+ (NetworkManager*)sharedNetworkManager
{
	@synchronized(self)
	{
		if(!_sharedNetworkManager)
		{
			_sharedNetworkManager = [[self alloc] init];
		}
	}
	return _sharedNetworkManager;
}

- (id)init
{
	if((self = [super init]))
	{
		// Init data
		requestCallbacks = [[NSMutableDictionary alloc] init];
	}
	return self;
}

#pragma mark -
#pragma mark Get timestamp
- (NSString*)getTimeStamp
{
	NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
	
	return [NSString stringWithFormat:@"%u", timeInterval];
}

#pragma mark -
#pragma mark isNetworkAvailable
- (BOOL)isNetworkAvailable
{
	WeiBoReachability* reachability = [WeiBoReachability sharedWeiBoReachability];
	
	NetworkStatus networkStatus = [reachability internetConnectionStatus];
	
	if(NotReachable == networkStatus)
	{
		return NO;
	}
	return YES;
}

#pragma mark -
#pragma mark requestServerForMethod
-(ASIFormDataRequest *)requestServerForMethod:(NetworkRequestType)methodType 
							   WithParameters:(NSDictionary *)parameters 
							 AndCallBackScope:(id)callBackDelegate 
								AndSuccessSel:(NSString *)successSelector 
								 AndFailedSel:(NSString *)failedSelector
{
	BOOL bIsNetworkAvailable = [self isNetworkAvailable];
	if(!bIsNetworkAvailable)
	{
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"貌似已于互联网断开链接"
														message:nil
													   delegate:nil
											  cancelButtonTitle:@"好的"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	else
	{   
		NSString* methodName = nil;
		NSString* requestURL = nil;
		switch (methodType)
		{
            case NetworkRequest_GetAppVersion:
            {
                methodName = @"GetAppVersion";
                requestURL = [NSString stringWithFormat:@"a=GetAppVersion&name=%@&model=%@&localizedModel=%@&systemName=%@&systemVersion=%@&uniqueIdentifier=%@",
                              [parameters objectForKey:@"name"],
                              [parameters objectForKey:@"model"],
                              [parameters objectForKey:@"localizedModel"],
                              [parameters objectForKey:@"systemName"],
                              [parameters objectForKey:@"systemVersion"],
                              [parameters objectForKey:@"uniqueIdentifier"]];
            }
                break;
            case NetworkRequest_CacheDeviceToken:
            {
                methodName = @"CacheDeviceToken";
                requestURL = [NSString stringWithFormat:@"a=CacheDeviceToken&uniqueIdentifier=%@&deviceToken=%@",
                              [parameters objectForKey:@"uniqueIdentifier"],
                              [parameters objectForKey:@"deviceToken"]];
            }
                break;
            case NetworkRequest_GetJourneyNews: // 最新资讯
            {
                methodName = @"GetJourneyNews";
                requestURL = [NSString stringWithFormat:@"a=journey_news&page_number=%@&page_size=%@", 
                              [parameters objectForKey:@"page_number"],
                              [parameters objectForKey:@"page_size"]];
            }
                break;
            case NetworkRequest_GetCategory: // 目录
            {
                methodName = @"GetCategory";
                requestURL = [NSString stringWithFormat:@"a=Category"];
            }
                break;
            case NetworkRequest_GetJourneyNewsByCategoryId:
            {
                methodName = @"GetJourneyNewsByCategoryId";
                requestURL = [NSString stringWithFormat:@"a=journeynewsbycategoryId&category_id=%@&page_number=%@&page_size=%@", 
                              [parameters objectForKey:@"category_id"],
                              [parameters objectForKey:@"page_number"],
                              [parameters objectForKey:@"page_size"]];
            }
                break;
            case NetworkRequest_GetJourneyInfo: // 行程信息
            {
                methodName = @"GetJourneyInfo";
                requestURL = [NSString stringWithFormat:@"a=journey_info&journeyId=%@", [parameters objectForKey:@"journeyId"]];
            }
                break;
            case NetworkRequest_GetJourneyIntroduction:// 根据journeyId获得行程简介
            {
                methodName = @"GetJourneyIntroduction";
                requestURL = [NSString stringWithFormat:@"a=journey_introduction&journeyId=%@", [parameters objectForKey:@"journeyId"]];
            }
                break;
            case NetworkRequest_GetJourneyDetails: // 根据journeyId&day获得行程参考
            {
                methodName = @"GetJourneyDetails";
                requestURL = [NSString stringWithFormat:@"a=journey_details&journeyId=%@&day=%@",
                              [parameters objectForKey:@"journeyId"],
                              [parameters objectForKey:@"day"]];
            }
                break;
            case NetworkRequest_GetJourneySightInfo: // 根据sight_name获得途径景点
            {
                methodName = @"GetJourneySightInfo";
                requestURL = [NSString stringWithFormat:@"a=sight_info&sight_name=%@",
                              [parameters objectForKey:@"sight_name"]];
            }
                break;
            case NetworkRequest_GetJourneyContactInfo:// 根据journeyId获得联系方式
            {
                methodName = @"GetJourneyContactInfo";
                requestURL = [NSString stringWithFormat:@"a=journey_contactinfo&journeyId=%@", [parameters objectForKey:@"journeyId"]];
            }
                break;
            case NetworkRequest_GetJourneyNotice:// 根据journeyId获得行程须知
            {
                methodName = @"GetJourneyNotice";
                requestURL = [NSString stringWithFormat:@"a=journey_notice&journeyId=%@", [parameters objectForKey:@"journeyId"]];
            }
                break;
            case NetworkRequest_GetMyFavoriteJourney: // 获取已经收藏的Journey
            {
                methodName = @"GetMyFavoriteJourney";
                requestURL = [NSString stringWithFormat:@"a=MyFavoriteJourney&page_number=%@&page_size=%@", 
                              [parameters objectForKey:@"page_number"],
                              [parameters objectForKey:@"page_size"]];
            }
                break;
            case NetworkRequest_UpdateOneJourneyToMyFavorite: // 更新Journey是否被收藏
            {
                methodName = @"UpdateOneJourneyToMyFavorite";
                requestURL = [NSString stringWithFormat:@"a=UpdateOneJourneyToMyFavorite&journey_id=%@&journey_isMyFavorite=%@", 
                              [parameters objectForKey:@"journey_id"],
                              [parameters objectForKey:@"journey_isMyFavorite"]];
            }
                break;
                /*****VISA*******/
            case NetworkRequest_GetVisaInfo:
            {
                methodName = @"GetVisaCountries";
                requestURL = @"a=GetVisaCountries";
            }
                break;
            case NetworkRequest_GetVisaAnswers:
            {
                methodName = @"GetVisaAnswers";
                requestURL = [NSString stringWithFormat:@"a=GetVisaAnswers&question_id=%@", 
                              [parameters objectForKey:@"question_id"]];
            }
                break;
            case NetworkRequest_GetVisaBaseAndNoticeInfo:
            {
                methodName = @"GetVisaBaseAndNoticeInfo";
                requestURL = [NSString stringWithFormat:@"a=GetVisaBaseAndNoticeInfo&countryId=%@&visaType=%@&visaAddress=%@",
                              [parameters objectForKey:@"countryId"],
                              [parameters objectForKey:@"visaType"],
                              [parameters objectForKey:@"visaAddress"]];
            }
                break;
            case NetworkRequest_GetVisaNeedPersonalId:
            {
                methodName = @"GetVisaNeedPersonalId";
                requestURL = [NSString stringWithFormat:@"a=GetVisaNeedPersonalId&countryId=%@&visaType=%@",
                              [parameters objectForKey:@"countryId"],
                              [parameters objectForKey:@"visaType"]];
            }
                break;
            case NetworkRequest_GetVisaNeedProperty:
            {
                methodName = @"GetVisaNeedProperty";
                requestURL = [NSString stringWithFormat:@"a=GetVisaNeedProperty&countryId=%@&visaType=%@",
                              [parameters objectForKey:@"countryId"],
                              [parameters objectForKey:@"visaType"]];
            }
                break;
            case NetworkRequest_GetVisaNeedEmployment:
            {
                methodName = @"GetVisaNeedEmployment";
                requestURL = [NSString stringWithFormat:@"a=GetVisaNeedEmployment&countryId=%@&visaType=%@",
                              [parameters objectForKey:@"countryId"],
                              [parameters objectForKey:@"visaType"]];
            }
                break;
            case NetworkRequest_GetVisaNeedStudentChildren:
            {
                methodName = @"GetVisaNeedStudentChildren";
                requestURL = [NSString stringWithFormat:@"a=GetVisaNeedStudentChildren&countryId=%@&visaType=%@",
                              [parameters objectForKey:@"countryId"],
                              [parameters objectForKey:@"visaType"]];
            }
                break;
            case NetworkRequest_GetVisaNeedElderly:
            {
                methodName = @"GetVisaNeedElderly";
                requestURL = [NSString stringWithFormat:@"a=GetVisaNeedElderly&countryId=%@&visaType=%@",
                              [parameters objectForKey:@"countryId"],
                              [parameters objectForKey:@"visaType"]];
            }
                break;
            case NetworkRequest_GetVisaNeedOthers:
            {
                methodName = @"GetVisaNeedOthers";
                requestURL = [NSString stringWithFormat:@"a=GetVisaNeedOthers&countryId=%@&visaType=%@",
                              [parameters objectForKey:@"countryId"],
                              [parameters objectForKey:@"visaType"]];
            }
                break;
			default:
				break;
		}
	
        requestURL = [APITRAVELACTION stringByAppendingString:requestURL];
        
        NSLog(@"requestURL=[%@]\n", requestURL);
        
		NSDictionary* tempDic = [[NSDictionary dictionaryWithObjectsAndKeys:
								  callBackDelegate, @"delegate", 
								  successSelector, @"onSuccess", 
								  failedSelector, @"onFailed", nil] retain];
		
		ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:requestURL]];
		request.requestFlagMark = [self getTimeStamp];
		request.ZooRequestType = methodType;
		
		[requestCallbacks setObject:tempDic forKey:request.requestFlagMark];
	
		[tempDic release];
		[request setDelegate:self];
		[request setDidFinishSelector:@selector(requestOnSuccess:)];
        [request setDidFailSelector:@selector(requestOnFailed:)];
		[request setRequestMethod:@"POST"];
		
		[request setPostValue:methodName forKey:@"method"];
		
		NSArray* parametersKey = [parameters allKeys];
		if([parametersKey count] > 0)
		{
			for(int i = 0; i < [parametersKey count]; i++)
			{
				[request setPostValue:[parameters objectForKey:[parametersKey objectAtIndex:i]] forKey:[parametersKey objectAtIndex:i]];
			}
		}
		[request startAsynchronous];
		
		return request;
	}
	return nil;
}

- (void)requestOnSuccess:(ASIFormDataRequest*)request
{
    NSString* response = [request responseString]; 
    
    //NSLog(@"%@\n", response);
	
	NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];
	
	NSDictionary* resultDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil];
	
	NSDictionary* targetCallBack = [requestCallbacks objectForKey:request.requestFlagMark];
	
	// 根据返回的数据进行相应的处理
	NSInteger nReturnCode = [[resultDic objectForKey:@"returnCode"] intValue];
	switch (nReturnCode)
	{
		case 1:
		{
			[[targetCallBack objectForKey:@"delegate"] performSelector:NSSelectorFromString([targetCallBack objectForKey:@"onSuccess"]) withObject:resultDic];
		}
			break;
		default:
		{
			[[targetCallBack objectForKey:@"delegate"] performSelector:NSSelectorFromString([targetCallBack objectForKey:@"onFailed"]) withObject:resultDic];
		}
			break;
	}
	
	// Clean up
	[requestCallbacks removeObjectForKey:request.requestFlagMark];
    
    // For stop loading
    [[MyLoadingView sharedMyLoadingView] stopLoadingAnimation];
}

#pragma mark -
#pragma mark requestOnFailed
- (void)requestOnFailed:(ASIFormDataRequest*)request
{	
	NSData* jsonData = [[request responseString] dataUsingEncoding:NSUTF8StringEncoding];
	
	NSDictionary* resultDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil];
    
	NSLog(@"requestOnFailed RESULT = %@", resultDic);
	
	[requestCallbacks removeObjectForKey:request.requestFlagMark];
    
    // For stop loading
    [[MyLoadingView sharedMyLoadingView] stopLoadingAnimation];
}

- (void)dealloc
{
	[requestCallbacks release];
	[_sharedNetworkManager release];
	
	[super dealloc];
}

@end
